package stackdemo;

import java.util.Stack;

//最小栈
class MinStack {
    private Stack<Integer> stack;
    private Stack<Integer> minStack;

    public MinStack() {
        stack = new Stack<>();
        minStack = new Stack<>();
    }

    public void push(int val) {
        stack.push(val);
        //判断minStack是否为空，空就放进元素，不为空，比较普通栈和最小栈的栈顶元素，如果普通栈的栈顶元素小于最小栈的栈顶元素，最小栈就放入元素
        if (minStack.empty()) {
            //最小栈为空
            minStack.push(val);
        } else {
            //最小栈不为空，进行判断
            int minVal = minStack.peek();
            if (val <= minVal) {
                minStack.push(val);
            }
        }
    }

    public void pop() {
        //普通栈：一定要删除，最小栈：看两者栈顶元素是否相同，相同删除，不相等就不删除
        int val = stack.pop();
        if (minStack.peek() == val) {
            minStack.pop();
        }
    }

    public int top() {
        return stack.peek();
    }

    public int getMin() {
        if(!minStack.empty()) {
            return minStack.peek();
        } else {
            return -1;
        }
    }
}
